package com.lingx.web.api.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.model.impl.DefaultEntity;
import com.lingx.service.ModelService;
import com.lingx.web.api.IApi;
@Component
public class Api9006 extends AbstractDevApi implements IApi{
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private ModelService modelService;
	@Override
	public int getApiCode() {
		return 9006;
	}
	@Override
	public String getApiName() {
		return "获取模型树形数据";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> param) {
		StringBuilder sb=new StringBuilder();
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String code=param.get("code").toString();
		DefaultEntity dm=this.modelService.getEntity(code);
		sb.append(dm.getId()).append(",");
		List<Map<String,Object>> roots=new ArrayList<>();
		Map<String,Object> root=new HashMap<>();
		root.put("id", dm.getId());
		root.put("code", dm.getCode());
		root.put("icon", dm.getIconCls());
		root.put("label", dm.getName()+" ["+dm.getCode()+"]");
		getChildren(root,dm,sb,1);
		roots.add(root);
		ret.put("data", roots);
		ret.put("expandedIds", sb.toString().split(","));

		ret.put("defaultCheckedKeys",dm.getId());// :default-checked-keys="defaultTreeNode"
		return ret;
	}
	
	private void getChildren(Map<String,Object> root,DefaultEntity dm,StringBuilder sb,int level){
		List<Map<String,Object>> list=this.modelService.getTreeList(dm, root.get("id").toString());
		for(Map<String,Object> m:list) {
			//if(level==1)sb.append(m.get("id").toString()).append(",");
			if(m.containsKey("expanded"))sb.append(m.get("id").toString()).append(",");
			this.getChildren(m, dm,sb,level+1);
		}
		if(list!=null&&list.size()>0)
		root.put("children", list);
		
	}

}
